import { ReactElement, useState, useEffect } from 'react'
import { Form, Row, Col, Select, DatePicker } from 'antd'
import style from './index.module.less'
import Dictionary, { DictionaryItem } from '@js/dictionary'

const { List, Item } = Form
const { Option } = Select

interface Props {
  name: string
}

function Main ({ name }: Props): ReactElement {
  const [options, setOptions] = useState<DictionaryItem[]>([])
  useEffect(() => {
    const d = new Dictionary()
    d.init('中止类型')
      .then(() => {
        setOptions(d.getList('中止类型'))
      })
      .catch(e => console.error(e))
  }, [])
  return (
    <List name={name}>
      {(fields, { add, remove }, { errors }) => (
        <>
          {
            fields.map((field, index) => {
              return (
                <div className={style.line} key={field.key}>
                  <Row className={style.input} gutter={24} justify='space-between'>
                    <Col span={8}>
                      <Item noStyle name={[field.name, 'type']} fieldKey={[field.key, 'type']}>
                        <Select placeholder='请选择' showSearch allowClear>
                          {
                            options.map((li, i) => {
                              return <Option key={i} value={li.value}>{li.title}</Option>
                            })
                          }
                        </Select>
                      </Item>
                    </Col>
                    <Col span={8}>
                      <Item noStyle name={[field.name, 'begin_datetime']} fieldKey={[field.key, 'begin_datetime']}>
                        <DatePicker className={style.full} />
                      </Item>
                    </Col>
                    <Col span={8}>
                      <Item noStyle name={[field.name, 'end_datetime']} fieldKey={[field.key, 'end_datetime']}>
                        <DatePicker className={style.full} />
                      </Item>
                    </Col>
                  </Row>
                  {
                    index === fields.length - 1
                      ? (
                      <div className={style['btn-block']} onClick={() => add()}>
                        <button className={style.btn} type='button'>+</button>
                      </div>
                        )
                      : (
                      <div className={style['btn-block']} onClick={() => remove(field.name)}>
                        <button className={style.btn} type='button'>-</button>
                      </div>
                        )
                  }
                </div>
              )
            })
          }
        </>
      )}
    </List>
  )
}

export default Main
